package webbandidong.validator;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
import webbandidong.bo.AdminBO;
import webbandidong.model.Admin;
import webbandidong.util.Constant;
import webbandidong.viewmodel.AdminChangePassViewModel;

public class AdminChangePasswordValidator implements Validator {

    @Autowired
    private AdminBO adminBO;

    public void setAdminBOImpl(AdminBO adminBO) {
        this.adminBO = adminBO;
    }

    public boolean supports(Class clazz) {
        return AdminChangePassViewModel.class.isAssignableFrom(clazz);
    }

    public void validate(Object target, Errors errors) {
        ValidationUtils.rejectIfEmpty(errors, "oldPassword", "required.oldPassword", "Old password is required");
        ValidationUtils.rejectIfEmpty(errors, "newPassword", "required.newPassword", "New password is required");
        ValidationUtils.rejectIfEmpty(errors, "confirmPassword", "required.confirmPassword", "Confirm password is required");

        if (!errors.hasErrors()) {
            AdminChangePassViewModel model = (AdminChangePassViewModel)target;

            if (!model.getNewPassword().equals(model.getConfirmPassword())) {
                errors.reject("password.notmatch");
            }

            String status = adminBO.checkExists(new Admin(0, model.getUsername(), model.getOldPassword()));
            if ("".equals(status)) {
                errors.reject("password.incorect");
            }
            else if (Constant.ERROR.equals(status)) {
                errors.reject("unexpected.failure");
            }
            System.out.println(status);
        }
    }
}
